<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline"
        @keyup.enter="onSubmit">
        <el-form-item label="创建日期" prop="createdAtRange">
          <template #label>
            <span>
              创建日期
              <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
                <el-icon>
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </span>
          </template>

          <el-date-picker v-model="searchInfo.createdAtRange" class="w-[380px]" type="datetimerange" range-separator="至"
            start-placeholder="开始时间" end-placeholder="结束时间" />
        </el-form-item>


        <template v-if="showAllQuery">
          <!-- 将需要控制显示状态的查询条件添加到此范围内 -->
        </template>

        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
          <el-button link type="primary" icon="arrow-down" @click="showAllQuery = true"
            v-if="!showAllQuery">展开</el-button>
          <el-button link type="primary" icon="arrow-up" @click="showAllQuery = false" v-else>收起</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button v-auth="btnAuth.add" type="primary" icon="plus" @click="openDialog()">新增</el-button>
        <el-button v-auth="btnAuth.batchDelete" icon="delete" style="margin-left: 10px;"
          :disabled="!multipleSelection.length" @click="onDelete">删除</el-button>

      </div>
      <el-table ref="multipleTable" style="width: 100%" tooltip-effect="dark" :data="tableData" row-key="ID"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />

        <!-- <el-table-column sortable align="left" label="日期" prop="CreatedAt" width="180">
          <template #default="scope">{{ formatDate(scope.row.CreatedAt) }}</template>
        </el-table-column> -->

        <el-table-column align="left" label="ID" prop="ID" width="120" />

        <el-table-column align="left" label="编码" prop="store_code" width="150" />

        <el-table-column align="left" label="名称" prop="store_name" width="150" />

        <el-table-column align="left" label="类型" prop="store_type" width="120">
          <template #default="scope">
            {{ scope.row.store_type === 1 ? '直营' : (scope.row.store_type === 2 ? '加盟' : (scope.row.store_type === 3 ? '合作' : '')) }}
          </template>
        </el-table-column>

        <el-table-column align="left" label="执照编号" prop="business_license" width="120" />
        <el-table-column align="left" label="执照起始" prop="license_start_date" width="150">
          <template #default="scope">{{ scope.row.license_start_date ? scope.row.license_start_date.split(' ')[0] : '' }}</template>
        </el-table-column>
        <el-table-column align="left" label="执照到期" prop="license_end_date" width="150">
          <template #default="scope">{{ scope.row.license_end_date ? scope.row.license_end_date.split(' ')[0] : '' }}</template>
        </el-table-column>
        <el-table-column align="left" label="药证编号" prop="pharmacy_license" width="150" />

        <el-table-column align="left" label="药证起始" prop="pharmacy_license_start" width="150">
          <template #default="scope">{{ scope.row.pharmacy_license_start ? scope.row.pharmacy_license_start.split(' ')[0] : '' }}</template>
        </el-table-column>
        <el-table-column align="left" label="药证到期" prop="pharmacy_license_end" width="150">
          <template #default="scope">{{ scope.row.pharmacy_license_end ? scope.row.pharmacy_license_end.split(' ')[0] : '' }}</template>
        </el-table-column>
        <el-table-column align="left" label="省份" prop="province" width="120" />

        <el-table-column align="left" label="城市" prop="city" width="120" />

        <el-table-column align="left" label="区县" prop="district" width="120" />

        <el-table-column align="left" label="地址" prop="address" width="120" />

        <el-table-column align="left" label="经度" prop="longitude" width="120" />

        <el-table-column align="left" label="纬度" prop="latitude" width="120" />

        <el-table-column align="left" label="联系人" prop="contact_person" width="120" />

        <el-table-column align="left" label="电话" prop="contact_phone" width="120" />

        <el-table-column align="left" label="营业时间" prop="business_hours" width="120" />

        <el-table-column align="left" label="门店状态" prop="store_status" width="120">
          <template #default="scope">
            <span v-if="scope.row.store_status === 1">营业中</span>
            <span v-else-if="scope.row.store_status === 2">停业</span>
            <span v-else-if="scope.row.store_status === 3">装修</span>
            <span v-else-if="scope.row.store_status === 4">已注销</span>
            <span v-else>未知</span>
          </template>
        </el-table-column>

        <el-table-column align="left" label="店长ID" prop="user_id" width="120" />

        <el-table-column align="left" label="备注" prop="remark" width="120" />

        <el-table-column align="left" label="操作" fixed="right" :min-width="appStore.operateMinWith">
          <template #default="scope">
            <el-button v-auth="btnAuth.info" type="primary" link class="table-button"
              @click="getDetails(scope.row)"><el-icon style="margin-right: 5px">
                <InfoFilled />
              </el-icon>查看</el-button>
            <el-button v-auth="btnAuth.edit" type="primary" link icon="edit" class="table-button"
              @click="updateSysStoresFunc(scope.row)">编辑</el-button>
            <el-button v-auth="btnAuth.delete" type="primary" link icon="delete"
              @click="deleteRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination layout="total, sizes, prev, pager, next, jumper" :current-page="page" :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]" :total="total" @current-change="handleCurrentChange"
          @size-change="handleSizeChange" />
      </div>
    </div>
    <el-drawer destroy-on-close :size="appStore.drawerSize" v-model="dialogFormVisible" :show-close="false"
      :before-close="closeDialog">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{ type === 'create' ? '新增' : '编辑' }}</span>
          <div>
            <el-button :loading="btnLoading" type="primary" @click="enterDialog">确 定</el-button>
            <el-button @click="closeDialog">取 消</el-button>
          </div>
        </div>
      </template>

      <el-form :model="formData" label-position="top" ref="elFormRef" :rules="rule" label-width="80px">
        <el-form-item label="编码:" prop="store_code">
          <el-input v-model="formData.store_code" :clearable="false" placeholder="请输入编码" />
        </el-form-item>
        <el-form-item label="名称:" prop="store_name">
          <el-input v-model="formData.store_name" :clearable="false" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="类型:" prop="store_type">
          <el-radio-group v-model="formData.store_type">
            <el-radio :label="1">直营</el-radio>
            <el-radio :label="2">加盟</el-radio>
            <el-radio :label="3">合作</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="执照编号:" prop="business_license">
          <el-input v-model="formData.business_license" :clearable="false" placeholder="请输入执照编号" />
        </el-form-item>
        <el-form-item label="执照起始:" prop="license_start_date">
          <el-date-picker v-model="formData.license_start_date" type="date" style="width:100%" placeholder="选择日期"
            :clearable="false" />
        </el-form-item>
        <el-form-item label="执照到期:" prop="license_end_date">
          <el-date-picker v-model="formData.license_end_date" type="date" style="width:100%" placeholder="选择日期"
            :clearable="false" />
        </el-form-item>
        <el-form-item label="药证编号:" prop="pharmacy_license">
          <el-input v-model="formData.pharmacy_license" :clearable="false" placeholder="请输入药证编号" />
        </el-form-item>
        <el-form-item label="药证起始:" prop="pharmacy_license_start">
          <el-date-picker v-model="formData.pharmacy_license_start" type="date" style="width:100%" placeholder="选择日期"
            :clearable="false" />
        </el-form-item>
        <el-form-item label="药证到期:" prop="pharmacy_license_end">
          <el-date-picker v-model="formData.pharmacy_license_end" type="date" style="width:100%" placeholder="选择日期"
            :clearable="false" />
        </el-form-item>
        <el-form-item label="省份:" prop="province">
          <el-input v-model="formData.province" :clearable="false" placeholder="请输入省份" />
        </el-form-item>
        <el-form-item label="城市:" prop="city">
          <el-input v-model="formData.city" :clearable="false" placeholder="请输入城市" />
        </el-form-item>
        <el-form-item label="区县:" prop="district">
          <el-input v-model="formData.district" :clearable="false" placeholder="请输入区县" />
        </el-form-item>
        <el-form-item label="地址:" prop="address">
          <el-input v-model="formData.address" :clearable="false" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="经度:" prop="longitude">
          <el-input-number v-model="formData.longitude" style="width:100%" :precision="2" :clearable="false" />
        </el-form-item>
        <el-form-item label="纬度:" prop="latitude">
          <el-input-number v-model="formData.latitude" style="width:100%" :precision="2" :clearable="false" />
        </el-form-item>
        <el-form-item label="联系人:" prop="contact_person">
          <el-input v-model="formData.contact_person" :clearable="false" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="电话:" prop="contact_phone">
          <el-input v-model="formData.contact_phone" :clearable="false" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="营业时间:" prop="business_hours">
          <el-input v-model="formData.business_hours" :clearable="false" placeholder="请输入营业时间" />
        </el-form-item>
        <el-form-item label="门店状态:" prop="store_status">
          <el-radio-group v-model="formData.store_status">
            <el-radio :label="1">营业中</el-radio>
            <el-radio :label="2">停业</el-radio>
            <el-radio :label="3">装修</el-radio>
            <el-radio :label="4">已注销</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="店长:" prop="user_id">
          <el-select v-model="formData.user_id" filterable placeholder="请选择店长" style="width:100%">
            <el-option
              v-for="item in userList"
              :key="item.ID"
              :label="`${item.userName}${item.nickName ? ' (' + item.nickName + ')' : ''}`"
              :value="item.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注:" prop="remark">
          <el-input v-model="formData.remark" :clearable="false" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
    </el-drawer>

    <el-drawer destroy-on-close :size="appStore.drawerSize" v-model="detailShow" :show-close="true"
      :before-close="closeDetailShow" title="查看">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="编码">
          {{ detailForm.store_code }}
        </el-descriptions-item>
        <el-descriptions-item label="名称">
          {{ detailForm.store_name }}
        </el-descriptions-item>
        <el-descriptions-item label="类型">
          {{ detailForm.store_type === 1 ? '直营' : (detailForm.store_type === 2 ? '加盟' : (detailForm.store_type === 3 ? '合作' : '')) }}
        </el-descriptions-item>
        <el-descriptions-item label="执照编号">
          {{ detailForm.business_license }}
        </el-descriptions-item>
        <el-descriptions-item label="执照起始">
          {{ detailForm.license_start_date ? formatDate(detailForm.license_start_date) : '' }}
        </el-descriptions-item>
        <el-descriptions-item label="执照到期">
          {{ detailForm.license_end_date ? formatDate(detailForm.license_end_date) : '' }}
        </el-descriptions-item>
        <el-descriptions-item label="药证编号">
          {{ detailForm.pharmacy_license }}
        </el-descriptions-item>
        <el-descriptions-item label="药证起始">
          {{ detailForm.pharmacy_license_start ? formatDate(detailForm.pharmacy_license_start) : '' }}
        </el-descriptions-item>
        <el-descriptions-item label="药证到期">
          {{ detailForm.pharmacy_license_end ? formatDate(detailForm.pharmacy_license_end) : '' }}
        </el-descriptions-item>
        <el-descriptions-item label="省份">
          {{ detailForm.province }}
        </el-descriptions-item>
        <el-descriptions-item label="城市">
          {{ detailForm.city }}
        </el-descriptions-item>
        <el-descriptions-item label="区县">
          {{ detailForm.district }}
        </el-descriptions-item>
        <el-descriptions-item label="地址">
          {{ detailForm.address }}
        </el-descriptions-item>
        <el-descriptions-item label="经度">
          {{ detailForm.longitude }}
        </el-descriptions-item>
        <el-descriptions-item label="纬度">
          {{ detailForm.latitude }}
        </el-descriptions-item>
        <el-descriptions-item label="联系人">
          {{ detailForm.contact_person }}
        </el-descriptions-item>
        <el-descriptions-item label="电话">
          {{ detailForm.contact_phone }}
        </el-descriptions-item>
        <el-descriptions-item label="营业时间">
          {{ detailForm.business_hours }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          {{
            detailForm.store_status === 1 ? '营业中'
            : detailForm.store_status === 2 ? '停业'
            : detailForm.store_status === 3 ? '装修'
            : detailForm.store_status === 4 ? '已注销'
            : '--'
          }}
        </el-descriptions-item>
        <el-descriptions-item label="店长ID">
          {{ detailForm.user_id }}
        </el-descriptions-item>
        <el-descriptions-item label="备注">
          {{ detailForm.remark }}
        </el-descriptions-item>
      </el-descriptions>
    </el-drawer>

  </div>
</template>

<script setup>
import {
  createSysStores,
  deleteSysStores,
  deleteSysStoresByIds,
  updateSysStores,
  findSysStores,
  getSysStoresList
} from '@/api/system/sysStores'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatBoolean, filterDict, filterDataSource, returnArrImg, onDownloadFile } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue'
// 引入按钮权限标识
import { useBtnAuth } from '@/utils/btnAuth'
import { useAppStore } from "@/pinia"




defineOptions({
  name: 'SysStores'
})
// 按钮权限实例化
const btnAuth = useBtnAuth()

// 提交按钮loading
const btnLoading = ref(false)
const appStore = useAppStore()

// 控制更多查询条件显示/隐藏状态
const showAllQuery = ref(false)

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
  store_code: '',
  store_name: '',
  store_type: 0,
  business_license: '',
  license_start_date: new Date(),
  license_end_date: new Date(),
  pharmacy_license: '',
  pharmacy_license_start: new Date(),
  pharmacy_license_end: new Date(),
  province: '',
  city: '',
  district: '',
  address: '',
  longitude: 0,
  latitude: 0,
  contact_person: '',
  contact_phone: '',
  business_hours: '',
  store_status: 0,
  user_id: 0,
  remark: '',
})



// 验证规则
const rule = reactive({
  store_code: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  {
    whitespace: true,
    message: '不能只输入空格',
    trigger: ['input', 'blur'],
  }
  ],
  store_name: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  {
    whitespace: true,
    message: '不能只输入空格',
    trigger: ['input', 'blur'],
  }
  ],
  store_type: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  ],
  business_license: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  {
    whitespace: true,
    message: '不能只输入空格',
    trigger: ['input', 'blur'],
  }
  ],
  license_start_date: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  ],
  license_end_date: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  ],
  pharmacy_license: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  {
    whitespace: true,
    message: '不能只输入空格',
    trigger: ['input', 'blur'],
  }
  ],
  pharmacy_license_start: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  ],
  pharmacy_license_end: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  ],
  province: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  {
    whitespace: true,
    message: '不能只输入空格',
    trigger: ['input', 'blur'],
  }
  ],
  city: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  {
    whitespace: true,
    message: '不能只输入空格',
    trigger: ['input', 'blur'],
  }
  ],
  district: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  {
    whitespace: true,
    message: '不能只输入空格',
    trigger: ['input', 'blur'],
  }
  ],
  address: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  {
    whitespace: true,
    message: '不能只输入空格',
    trigger: ['input', 'blur'],
  }
  ],
  contact_person: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  {
    whitespace: true,
    message: '不能只输入空格',
    trigger: ['input', 'blur'],
  }
  ],
  contact_phone: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  {
    whitespace: true,
    message: '不能只输入空格',
    trigger: ['input', 'blur'],
  }
  ],
  store_status: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  ],
})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})
// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async (valid) => {
    if (!valid) return
    page.value = 1
    getTableData()
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async () => {
  const table = await getSysStoresList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () => {
}

// 获取需要的字典 可能为空 按需保留
setOptions()


// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 删除行
const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteSysStoresFunc(row)
  })
}

// 多选删除
const onDelete = async () => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const IDs = []
    if (multipleSelection.value.length === 0) {
      ElMessage({
        type: 'warning',
        message: '请选择要删除的数据'
      })
      return
    }
    multipleSelection.value &&
      multipleSelection.value.map(item => {
        IDs.push(item.ID)
      })
    const res = await deleteSysStoresByIds({ IDs })
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
      if (tableData.value.length === IDs.length && page.value > 1) {
        page.value--
      }
      getTableData()
    }
  })
}

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

// 更新行
const updateSysStoresFunc = async (row) => {
  const res = await findSysStores({ ID: row.ID })
  type.value = 'update'
  if (res.code === 0) {
    formData.value = res.data
    dialogFormVisible.value = true
  }
}


// 删除行
const deleteSysStoresFunc = async (row) => {
  const res = await deleteSysStores({ ID: row.ID })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    getTableData()
  }
}

// 弹窗控制标记
const dialogFormVisible = ref(false)

// 打开弹窗
const openDialog = () => {
  type.value = 'create'
  dialogFormVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    store_code: '',
    store_name: '',
    store_type: 0,
    business_license: '',
    license_start_date: new Date(),
    license_end_date: new Date(),
    pharmacy_license: '',
    pharmacy_license_start: new Date(),
    pharmacy_license_end: new Date(),
    province: '',
    city: '',
    district: '',
    address: '',
    longitude: 0,
    latitude: 0,
    contact_person: '',
    contact_phone: '',
    business_hours: '',
    store_status: 0,
    user_id: 0,
    remark: '',
  }
}
// 弹窗确定
const enterDialog = async () => {
  btnLoading.value = true
  elFormRef.value?.validate(async (valid) => {
    if (!valid) return btnLoading.value = false
    let res
    switch (type.value) {
      case 'create':
        res = await createSysStores(formData.value)
        break
      case 'update':
        res = await updateSysStores(formData.value)
        break
      default:
        res = await createSysStores(formData.value)
        break
    }
    btnLoading.value = false
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '创建/更改成功'
      })
      closeDialog()
      getTableData()
    }
  })
}

const detailForm = ref({})

// 查看详情控制标记
const detailShow = ref(false)


// 打开详情弹窗
const openDetailShow = () => {
  detailShow.value = true
}


// 打开详情
const getDetails = async (row) => {
  // 打开弹窗
  const res = await findSysStores({ ID: row.ID })
  if (res.code === 0) {
    detailForm.value = res.data
    openDetailShow()
  }
}


// 关闭详情弹窗
const closeDetailShow = () => {
  detailShow.value = false
  detailForm.value = {}
}


</script>

<style></style>
